
#import "HelenHttpClient.h"

#define TIMEOUT 18.0


@implementation HelenParametersDic

+ (id)h_dictionary
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"i"] = @"10";
    dict[@"c"] = @"entry";
    dict[@"m"] = @"bz_activities";
    dict[@"ctrl"] = @"live_merch";
    return dict;
}

@end



@implementation HelenFormData

@end



@implementation HelenHttpClient

//请求队列管理者 单例创建形式 防止内存泄漏
+ (AFHTTPSessionManager*)defaultHTTPSessionManager {
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager  = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = TIMEOUT;
        //普通的http的编码格式 mid=10&dateInt=20160818
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    });
    return manager;
}


////请求队列管理者
+ (AFHTTPSessionManager*)defaultHTTPSessionManager_json {
    static AFHTTPSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager  = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = TIMEOUT;
        //json编码格式 {"mid":"11","method":"userInfo","dateInt":"20160818"}
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
//        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    });
    return manager;
}



+ (AFURLSessionManager*)defaultURLSessionManager {
    static AFURLSessionManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        AFHTTPResponseSerializer *responseSerializer = (AFHTTPResponseSerializer *)manager.responseSerializer;
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    });
    return manager;
}




/**发送一个请求(不上传文件数据)*/
+ (void)requestWithUrlString:(NSString *)urlString andParam:(NSMutableDictionary *)param andMethod:(NSString *)method progress:(ProgressBlock)progressBlock success:(SucessBlock)sucessBlock andFailBlock:(FailBlock)failBolck
{
//    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
//    manager.requestSerializer.timeoutInterval = TIMEOUT;
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    
    AFHTTPSessionManager *manager  = [self defaultHTTPSessionManager];
    NSOperationQueue * operationQueue = manager.operationQueue;
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                if(failBolck){
                    failBolck(0,nil);
                }
                break;
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    
    if ([method isEqualToString:@"GET"]) { //发送一个GET请求
        [manager GET:urlString parameters:param /**progress:^(NSProgress * _Nonnull downloadProgress) {
            if(progressBlock){
                progressBlock(downloadProgress);
            }
        }*/ success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(sucessBlock){
               sucessBlock(responseObject);
            }

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSError * realError = nil;
            if (error.userInfo[@"NSUnderlyingError"]) {
                realError = error.userInfo[@"NSUnderlyingError"];
            }else{

                realError = error;
            }
            if(failBolck){
                failBolck(realError.code,error);
            }

        }];
        
        
    }else if ([method isEqualToString:@"POST"]){
        
        [manager POST:urlString parameters:param /**progress:^(NSProgress * _Nonnull uploadProgress) {
            if(progressBlock){
                progressBlock(uploadProgress);
            }

        }*/ success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(sucessBlock){
                sucessBlock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSError * realError = nil;
            if (error.userInfo[@"NSUnderlyingError"]) {
                realError = error.userInfo[@"NSUnderlyingError"];
            }else{

                realError = error;
            }

            if(failBolck){
                failBolck(realError.code,error);
            }
        }];
        
    }

}




/**发送一个请求(不上传文件数据) json格式参数*/
+ (void)json_requestWithUrlString:(NSString *)urlString andParam:(NSMutableDictionary *)param andMethod:(NSString *)method progress:(ProgressBlock)progressBlock success:(SucessBlock)sucessBlock andFailBlock:(FailBlock)failBolck
{
    //    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    //    manager.requestSerializer.timeoutInterval = TIMEOUT;
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    
    AFHTTPSessionManager *manager  = [self defaultHTTPSessionManager_json];
    NSOperationQueue * operationQueue = manager.operationQueue;
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [operationQueue setSuspended:NO];
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [operationQueue setSuspended:YES];
                if(failBolck){
                    failBolck(0,nil);
                }
                break;
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    
    if ([method isEqualToString:@"GET"]) { //发送一个GET请求
        [manager GET:urlString parameters:param /**progress:^(NSProgress * _Nonnull downloadProgress) {
            if(progressBlock){
                progressBlock(downloadProgress);
            }
        }*/ success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(sucessBlock){
                sucessBlock(responseObject);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSError * realError = nil;
            if (error.userInfo[@"NSUnderlyingError"]) {
                realError = error.userInfo[@"NSUnderlyingError"];
            }else{
                
                realError = error;
            }
            if(failBolck){
                failBolck(realError.code,error);
            }
            
            
        }];
        
    }else if ([method isEqualToString:@"POST"]){
        
        [manager POST:urlString parameters:param /**progress:^(NSProgress * _Nonnull uploadProgress) {
            if(progressBlock){
                progressBlock(uploadProgress);
            }
            
        }*/ success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if(sucessBlock){
                sucessBlock(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSError * realError = nil;
            if (error.userInfo[@"NSUnderlyingError"]) {
                realError = error.userInfo[@"NSUnderlyingError"];
            }else{
                
                realError = error;
            }
            
            if(failBolck){
                failBolck(realError.code,error);
            }
        }];
        
    }
    
}





/**发送一个POST请求(上传文件数据)*/
+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params formDataArray:(NSArray *)formDataArray progress:(ProgressBlock)progressBlock success:(SucessBlock)sucessBlock failure:(FailBlock)failureBlock
{
    //建立一个能上传文件的请求
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if(formDataArray.count){ //有上传文件
            for (HelenFormData *helenData in formDataArray) {//遍历需要上传的文件的参数
                if(helenData.data){ //上传的是文件data
                    [formData appendPartWithFileData:helenData.data name:helenData.paramName fileName:helenData.filename mimeType:helenData.mimeType];
                }else{//上传的是文件的路径 fileURLWithPath:@"file://path/to/image.jpg"]
                    [formData appendPartWithFileURL:[NSURL fileURLWithPath:helenData.filepath] name:helenData.paramName fileName:helenData.filename mimeType:helenData.mimeType error:nil];
                }
                
            }
        }
        
    } error:nil];
    
    
    // AFURLSessionManager – 创建和管理 NSURLSession 对象
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    AFHTTPResponseSerializer *responseSerializer = (AFHTTPResponseSerializer *)manager.responseSerializer;
//    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    
    AFURLSessionManager *manager = [self defaultURLSessionManager];
    
    //创建一个上传任务
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (error) {//失败
            NSError * realError = nil;
            if (error.userInfo[@"NSUnderlyingError"]) {
                realError = error.userInfo[@"NSUnderlyingError"];
            }else{

                realError = error;
            }
            if(failureBlock){
                failureBlock(realError.code,error);
            }


        } else {// 成功
            if(sucessBlock){
                sucessBlock(responseObject);
            }

        }
    }];
    
    [uploadTask resume];
}




/**发送一请求(下载文件数据)*/
+ (void)downLoadTaskWithURL:(NSString *)url progress:(ProgressBlock)progressBlock
{
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    AFHTTPResponseSerializer *responseSerializer = (AFHTTPResponseSerializer *)manager.responseSerializer;
//    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", nil];
    
    AFURLSessionManager *manager = [self defaultURLSessionManager];
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    //创建一个下载任务
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //文件保存路径
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];

    
    [downloadTask resume];
}

@end
